package c04.thread.activity;

import lombok.extern.slf4j.Slf4j;
import util.Sleeper;

/**
 * 死锁：一个线程需要同时获取多把锁，就容易发生死锁
 *
 * 解决方法: 使用ReentrantLock解决
 */
@Slf4j(topic = "c.DeadLockTest")
public class DeadLock {
    public static void main(String[] args) {
        Object A = new Object();
        Object B = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (A) {
                log.debug("lock A");
                Sleeper.sleep(1);
                synchronized (B) {
                    log.debug("lock B");
                    log.debug("操作...");
                }
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            synchronized (B) {
                log.debug("lock B");
                Sleeper.sleep(0.5);
                synchronized (A) {
                    log.debug("lock A");
                }
            }
        }, "t2");

        t1.start();
        t2.start();
    }
}
